package com.ashlikun.xviewpager.simple

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.ashlikun.glideutils.GlideLoad
import com.ashlikun.glideutils.GlideUtils
import com.ashlikun.glideutils.GlideUtils.init
import com.bumptech.glide.request.target.ImageViewTarget
import com.bumptech.glide.request.transition.Transition

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        init(applicationContext, null)
        GlideUtils.errorRes = R.mipmap.ic_launcher
        setContentView(R.layout.activity_main)
        val imageView = findViewById<ImageView>(R.id.imageView)
        GlideLoad.with(imageView)
            .load("https://vinkalife-1255635395.cos.ap-hongkong.myqcloud.com/app/img/model/model-2.png")
            .show(MyImageViewTarget(imageView, "https://vinkalife-1255635395.cos.ap-hongkong.myqcloud.com/app/img/model/model-2.png"))
    }

    companion object {
        private val RESURL = arrayOf<Any>(
            "http://img.mukewang.com/54bf7e1f000109c506000338-590-330.jpg",
            "http://upload.techweb.com.cn/2015/0114/1421211858103.jpg",
            "http://img1.cache.netease.com/catchpic/A/A0/A0153E1AEDA115EAE7061A0C7EBB69D2.jpg",
            "http://image.tianjimedia.com/uploadImages/2015/202/27/57RF8ZHG8A4T_5020a2a4697650b89" +
                    "c394237ba9ffbb45fe8555a2cbec-6O6nmI_fw658.jpg"
        )
        private val RESURL2 = arrayOf<Any>(
            "http://img.zcool.cn/community/0117e2571b8b246ac72538120dd8a4.jpg@1280w_1l_2o_100sh.jpg"
        )
    }
}

/**
 * 这里判断缓存是否存在，如果存在就不使用占位图
 */
class MyImageViewTarget(val imageView: ImageView, val url: String?) : ImageViewTarget<Drawable>(imageView) {
    val hasCache by lazy { GlideUtils.isCache(url) }
    var start = System.currentTimeMillis()

    override fun setResource(resource: Drawable?) {
        view.setImageDrawable(resource)
    }

    override fun setDrawable(drawable: Drawable?) {
        super.setDrawable(drawable)
    }

    override fun onResourceReady(resource: Drawable, transition: Transition<in Drawable>?) {
        super.onResourceReady(resource, transition)
        Log.e("dddddd", "wwwwwwwwwww onResourceReady ${System.currentTimeMillis() - start}")
    }

    override fun onLoadFailed(errorDrawable: Drawable?) {
        super.onLoadFailed(errorDrawable)
    }

    override fun onLoadStarted(placeholder: Drawable?) {
//        start = System.currentTimeMillis()
        //这里判断缓存是否存在，如果存在就不使用占位图
        if (placeholder != null && !hasCache) {
            super.onLoadStarted(placeholder)
        } else {
            //还原
        }
    }

}